package com.sunye.test;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import sun.misc.BASE64Encoder;
import org.apache.commons.io.IOUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

@RestController
@RequestMapping("/testController")
public class testController {


    private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }

    /**
     * 将文件流转换成base64
     * @param request
     * @return
     */
    @RequestMapping("/fileToBase64")
    public static String fileToBase64(HttpServletRequest request){
        //获取文件流
        InputStream inputStream = null;
        BufferedInputStream bis = null;
        byte[] temp = null;
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("file");//获取参数名
            if (multipartFile == null || multipartFile.getSize() == 0) {
                throw new IOException("上传文件不存在");
            }
            if (multipartFile.getSize() > 4096 * 1024) {
                throw new IOException("上传文件不能超过4M");
            }
            inputStream = multipartFile.getInputStream();
            temp = IOUtils.toByteArray(inputStream);//输入流变成字节
//            //缓冲区形式（BufferedInputStream）
//            bis = new BufferedInputStream(inputStream);
//            temp = new byte[bis.available()];
//            bis.read(temp);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally { // 关闭流资源
            try {
//                bis.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //将文件流字节转化为base64
        String base64Str = "";
        try {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            base64Str = base64Encoder.encode(temp);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  base64Str;
    }



    //将网络图片转转换成base64
    @RequestMapping("/encodeToString")
    public  String encodeToString(String imgURL) {
        InputStream in = null;
        CloseableHttpResponse response = null;
        byte[] temp = null;
        try {
            // 创建链接
            //采用绕过验证的方式处理https请求
            SSLContext sslcontext = null;
            try {
                sslcontext = createIgnoreVerifySSL();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            } catch (KeyManagementException e) {
                e.printStackTrace();
            }
            // 设置协议http和https对应的处理socket链接工厂的对象
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);
            CloseableHttpClient client = HttpClients.custom().setConnectionManager(connManager).build();
            //HttpPost httpPost = new HttpPost(imgURL);
            HttpGet httpPost = new HttpGet(imgURL);
            //指定报文头【Content-type】、【User-Agent】
            //httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            //httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36");

            //执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpPost);
            in = response.getEntity().getContent();
            temp = IOUtils.toByteArray(in);
//            byte[] buffer = new byte[521];
//            ByteArrayOutputStream baos = new ByteArrayOutputStream();
//            for (int len = 0; (len = in.read(buffer)) > 0; ) {
//                baos.write(buffer, 0, len);
//            }
//            temp = baos.toByteArray();
            // 对字节数组Base64编码
            BASE64Encoder encoder = new BASE64Encoder();
            String subImg = imgURL.substring(imgURL.lastIndexOf(".") + 1, imgURL.length());
            // 返回Base64编码过的字节数组字符串
            StringBuilder sb = new StringBuilder();
            sb.append("data:image" + subImg + ";base64,");
            sb.append(encoder.encode(temp));
            return sb.toString();
        } catch (IOException e) {
            e.printStackTrace();
            return "";
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
